import { init, h } from 'snabbdom'
import style from 'snabbdom/modules/style'
import eventlisteners from 'snabbdom/modules/eventlisteners'

let patch = init([
  style,
  eventlisteners
])

let movieData = [
  {
    rank: 2,
    title: "星际穿越",
    description: "最好看的科幻片",
  },
  {
    rank: 3,
    title: "蝙蝠侠：黑暗骑士",
    description: "最好看的动作片",
  },
  {
    rank: 1,
    title: "盗梦空间",
    description: "最好看的悬疑片",
  },
  {
    rank: 4,
    title: "拯救大兵瑞恩",
    description: "最好看的战争片",
  },
]
let listNodeArr = []
let updateNodeArr = () => {
  listNodeArr = movieData.map((v, key) => {
    return h('div', {
      key,
      style: {
        backgroundColor: '#1E1C19',
        width: "100%",
        height: "120px",
        display: "flex",
        alignItems: "center",
        justifyContent: "space-between",
        marginBottom: "10px",
        padding: "0px 50px",
        boxSizing: "border-box"
      },
    }, [
      h('div', v.rank),
      h('div', v.title),
      h('div', v.description),
    ])
  });
}

updateNodeArr()

let vnode = h('div', {
  style: {
    width: "100%",
    color: "#FFFEDE",
    fontSize: "23px"
  },
}, listNodeArr)

let movieListBlock = document.querySelector('#movie-list')

let oldVnode = patch(movieListBlock, vnode)

let addDiv = document.querySelector('#add-button');
addDiv.addEventListener('click', () => {
  movieData.push({
    rank: 5,
    title: "信条",
    description: "最期待的科幻片",
  })
  updateNodeArr()
  let vnode2 = h('div', {
    style: {
      width: "100%",
      color: "#FFFEDE",
      fontSize: "23px"
    },
  }, listNodeArr)
  oldVnode = patch(oldVnode, vnode2)
})

let compareUtil = (propertyName) => {
  return function (obj1, obj2) {
    let v1 = obj1[propertyName];
    let v2 = obj2[propertyName];
    if (v1 < v2) {
      return -1;
    } else if (v1 > v2) {
      return 1;
    } else {
      return 0;
    }
  };
};
let sortList = (sortKey) => {
  console.log("111111111");
  movieData.sort(compareUtil(sortKey))
  updateNodeArr()
  let newVnode = h('div', {
    style: {
      width: "100%",
      color: "#FFFEDE",
      fontSize: "23px"
    },
  }, listNodeArr)
  oldVnode = patch(oldVnode, newVnode)
}
let rankDiv = document.querySelector('#sort-rank');
let titleDiv = document.querySelector('#title-rank');
let desDiv = document.querySelector('#des-rank');
rankDiv.addEventListener('click', () => {
  sortList("rank")
})
titleDiv.addEventListener('click', () => {
  sortList("title")
})
desDiv.addEventListener('click', () => {
  sortList("description")
})

